package com.itheima.service.impl;

import com.itheima.mapper.DeptLogMapper;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Dept;
import com.itheima.pojo.DeptLog;
import com.itheima.pojo.Result;
import com.itheima.service.DeptService;
import com.itheima.utils.JWTUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private DeptLogMapper deptLogMapper;

    @Autowired
    private HttpServletRequest request;

    @Override
    public List<Dept> list() {
        List<Dept> deptList = deptMapper.list();
        log.info("deptList:{}",deptList);
        return deptList;
    }

    @Override
    public void add(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.add(dept);
    }

    @Override
    public boolean findDeptName(String deptName) {
        String name = deptMapper.findDeptName(deptName);
        if(name != null) {
            return true;
        }
        return false;
    }

    @Override
    @Transactional
    public void delete(Integer id) {
        Dept dept = deptMapper.findById(id);
        //解析token 获取员工username
        String token = request.getHeader("token");
        Claims claims = JWTUtils.parseJwt(token);
        String username = (String) claims.get("username");
        try {
            deptMapper.delete(id);
            empMapper.deleteByDeptId(id);
        }finally {
            DeptLog deptLog = new DeptLog();
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("员工" + username + "执行了解散部门操作，部门名称：" + dept.getName() + "，是"+id+"号部门。");
            deptLogMapper.insert(deptLog);
        }

    }

    @Override
    public Dept findById(Integer id) {
        Dept dept = deptMapper.findById(id);
        return dept;
    }

    @Override
    public void update(Dept dept) {
        deptMapper.update(dept);
    }
}
